package com.chalk.common.advice;

import com.chalk.common.exception.ServiceException;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;

/**
 * 描述：全局统一异常处理
 *
 * @author He Yong
 * @version 1.0
 * @since 2017/10/27
 */
@Order(Integer.MIN_VALUE)
@RestControllerAdvice
public class GlobalExceptionHandlerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandlerAdvice.class);

    /**
     * bean validator 校验异常
     */
    @ExceptionHandler(ValidationException.class)
    public Result handlerValidationException(ValidationException e, HttpServletRequest request) {
        if (logger.isDebugEnabled()) {
            logger.debug("uri = {} | exception message = {}", request.getRequestURI(), e.getMessage());
        }
        // Bean校验错误不上报到钉钉机器人
        return Result.fail(ResultCode.PARAM_IS_INVALID.msg(), e.getMessage());
    }

    /**
     * 自定义返回异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public Result handlerServiceException(ServiceException e, HttpServletRequest request) {
        if (logger.isDebugEnabled()) {
            logger.debug("uri = {} | exception code = {}", request.getRequestURI(), e.getCode());
        }
        return Result.custom(e.getCode(),e.getMsg(),null);
    }

}
